#--coding:utf-8--
# @Time    : 2022/4/28/028 23:10
# @Author  : hakold
# @File    : exp_level_model.py
# @PROJECT : chatroom_game

import json
import pymongo
from model import player_model

global level_exp_config
level_exp_config = json.load(open("config/level_exp.json", encoding='utf-8'))


def mongo_connect():
    #myclient = pymongo.MongoClient('mongodb+srv://hakold:52Beebee@cluster0.gy1rb.mongodb.net/xiuxian?retryWrites=true&w=majority/')
    myclient = pymongo.MongoClient('mongodb://127.0.0.1:27017/')
    #dblist = myclient.list_database_names()
    # dblist = myclient.database_names() 
    mydb = myclient["qt_game"] #创建数据库
    #collist = mydb.list_collection_names()
    mycol = mydb["player"] #集合
    return mycol

def check(data_dict):  # 获取经验信息
    # inner_type = data_dict["inner_type"].strip()
    data = {}
    account = data_dict['account']
    mycol = mongo_connect()
    check_query = { "account" : account }
    check_doc = mycol.find(check_query)
    check_list = []
    for x in check_doc:
        check_list.append(x)
    player_data = check_list[0]
    del player_data["_id"]
    code = "200"
    data["account"] = player_data["account"]
    data["type"] = "exp_renew"
    data["code"] = code
    data["data"] = player_data
    data = json.dumps(data)
    return data

def level_up(self, account):
    # 升级逻辑
    mycol = mongo_connect()
    check_query = { "account" : account }
    check_doc = mycol.find(check_query)
    check_list = []
    for x in check_doc:
        check_list.append(x)
    player_data = check_list[0]
    del player_data["_id"]
    if player_data['level']+1 <= 24:
        # 现在最多是24
        if player_data['exp'] >= level_exp_config[str(player_data['level']+1)]['upgrade_need']:
            # 玩家可以突破
            player_model.player_attribute_change(self, player_data['account'], 'level', int(1))
            return True
        else:
            # 玩家不可以突破
            return False

def exp_auto_up(account):
    # 自动获得经验逻辑
    mycol = mongo_connect()
    exp_level_config = json.load(open("config/level_exp.json", encoding='utf-8'))
    check_query = { "account" : account }
    check_doc = mycol.find(check_query)
    check_list = []
    for x in check_doc:
        check_list.append(x)
    player_data = check_list[0]
    del player_data["_id"]
    auto_exp_value = exp_level_config[str(player_data["level"])]["auto_exp_value"]
    old_exp_value = player_data["exp"]
    new_exp_value = old_exp_value + auto_exp_value
    newvalues = { "$set": { "exp": int(new_exp_value) } }
    mycol.update_one({ "account" : player_data["account"] }, newvalues)
    print("用户" + player_data["account"] +"增加完成")